﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.MenuCommand;
using D.Medicalcare.Read.API.Dtos;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.MenuHandler
{
    /// <summary>
    /// 菜单分页显示处理
    /// </summary>
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, APIPaging<MenuDTO>>
    {
        private readonly IBaseRepository<Menu> menuRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="menuRep"></param>
        public GetMenuHandler(IBaseRepository<Menu> menuRep)
        {
            this.menuRep = menuRep;
        }
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">命令</param>
        /// <returns>APIPaging</returns>
        public async Task<APIPaging<MenuDTO>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            APIPaging<MenuDTO> result = new APIPaging<MenuDTO>();
            var m = menuRep.GetAll();
            Menu menu = new Menu
            {
                MenuId = 0,
                MenuName = " ",
                ParentId = -1,
                MenuUrl = "",
                CreateTime = DateTime.Now,
                CreateUserId = 0,
                UpdateUserId = 0,
                UpdateTime = DateTime.Now,
            };
            var m2 = m.ToList();
            m2.Add(menu);
            var linq = from a in m2
                       join b in m2 on a.ParentId equals b.MenuId
                       where a.IsDeleted == false
                       select new MenuDTO
                       {
                           MenuId = a.MenuId,
                           MenuName = a.MenuName,
                           MenuUrl = a.MenuUrl,
                           CreateTime = a.CreateTime,
                           CreateName = a.CreateUserId.ToString(),
                           UpdateName = a.UpdateUserId.ToString(),
                           UpdateTime = a.UpdateTime,
                           ParentId = a.ParentId,
                           ParentName = b.MenuName,
                           OrderById = a.OrderById
                       };

            result.Code = APIEnum.Mvc;
            result.Msg = "显示成功";
            result.TotalCount = linq.Count();
            result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
            result.Data = linq.OrderBy(a => a.OrderById).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return await Task.FromResult(result);
        }

    }
}
